using System.Web.UI;
using System;
using System.Collections.Generic;
using System.Collections;

namespace Web.Ajax.Controls
{
	public class AjaxControl : System.Web.UI.WebControls.CompositeControl, IJavascriptControl
	{
		#region RenderTitle
		/// <summary>
		/// Render the PopupTitle Control if it is not null. 
		/// </summary>
		/// <param name="writer">A HtmlTextWriter</param>
		protected void RenderTitle(HtmlTextWriter writer, Type parent)
		{
            if (PopupTitle != null)
            {
                if(parent==typeof(AjaxGrid))
                {
                    if(PopupTitle.TitleLeft!=null)
                        PopupTitle.TitleLeft.CssClass = "GridTitleLeft";
                    if (PopupTitle.TitleMiddle != null)
                        PopupTitle.TitleMiddle.CssClass = "GridTitleMiddle";
                    if (PopupTitle.TitleRight != null)
                        PopupTitle.TitleRight.CssClass = "GridTitleRight";
                }
                PopupTitle.Render(writer, JavascriptId);
            }
		}
		#endregion

		#region PopupTitle
		private PopupTitle popupTitle;
		public PopupTitle PopupTitle
		{
			get
			{
				if (popupTitle == null)
				{
					for (int i = 0; i < Controls.Count; i++)
					{
						if (Controls[i] is PopupTitle)
							popupTitle = (Controls[i] as PopupTitle);
					}

				}
				return popupTitle;
			}
		}
		#endregion

        #region Paramters
        private Parameter[] parameters;
        public Parameter[] Parameters
        {
            get
            {
                if (parameters == null)
                {
                    List<Parameter> p = new List<Web.Ajax.Controls.Parameter>();
                    for (int i = 0; i < Controls.Count; i++)
                    {
                        if (Controls[i] is Web.Ajax.Controls.Parameter)
                            p.Add(Controls[i] as Web.Ajax.Controls.Parameter);
                    }
                    parameters = p.ToArray();
                }
                return parameters;
            }
        }
        #endregion

        public void SetParameter(string Name, string Value)
        {
            if (string.IsNullOrEmpty(Name))
                return;
            if (Parameters != null)
            {
                for (int i = 0; i < Parameters.Length; i++)
                {
                    Parameter p = Parameters[i];
                    if (p.Name == Name)
                    {
                        p.Value = Value;
                        return;
                    }
                }
            }
            Controls.Add(new Parameter(Name, Value));
            parameters = null;
        }


		public void ProcessParameterClientIds()
		{
			Parameter[] p = Parameters;
			if (p == null || p.Length == 0)
				return;
			for (int i = 0; i < p.Length; i++)
			{
				string id = p[i].Source;
				if (!string.IsNullOrEmpty(id))
				{
					Control c = Parent.FindControl(id);
					if (c == null && PopupTitle != null)
						c = PopupTitle.FindControl(id);
					if (c == null && PopupTitle != null)
					{
						for (int j = 0; j < PopupTitle.Controls.Count; j++)
						{
							c = PopupTitle.Controls[j].FindControl(id);
							if (c != null)
								break;
						}
					}
					if (c != null)
					{
						string SrcId;
						if (c is IJavascriptControl)
						{
							IJavascriptControl ij = (IJavascriptControl)c;
							SrcId = ij.JavascriptId;
						}
						else
							SrcId = c.ClientID;
						p[i].Source = SrcId;
					}
				}
			}
		}

        #region RenderParameters
        public void RenderParameters(HtmlTextWriter writer)
        {
			ProcessParameterClientIds();
            Parameter[] p = Parameters;
            if (p == null || p.Length == 0)
                return;
            writer.Write(JavascriptId + ".Parameters=[");
            for (int i = 0; i < p.Length; i++)
            {
				
                if (i > 0)
                    writer.Write(",");
				/*
                string id = p[i].Source;
                if (!string.IsNullOrEmpty(id))
                {
                    Control c = Parent.FindControl(id);
                    if (c == null && PopupTitle != null)
                        c = PopupTitle.FindControl(id);
                    if (c == null && PopupTitle != null)
                    {
                        for (int j = 0; j < PopupTitle.Controls.Count; j++)
                        {
                            c = PopupTitle.Controls[j].FindControl(id);
                            if (c != null)
                                break;
                        }
                    }
					if (c != null)
					{
						string SrcId;
						if (c is IJavascriptControl)
						{
							IJavascriptControl ij = (IJavascriptControl)c;
							SrcId = ij.JavascriptId;
						}
						else
							SrcId = c.ClientID;
						p[i].Source = SrcId;
					}
                }*/
                writer.Write(p[i].ConvertToJson());
            }
            writer.Write("];\n");
        }
        #endregion

        private bool passPageParameters = false;
        public bool PassPageParameters
        {
            get
            {
                return passPageParameters;
            }
            set
            {
                passPageParameters = value;
            }
        }

        #region NoData
        private string noData = "No Data";
        /// <summary>
        /// The Message to display when there is no data.
        /// </summary>
        public string NoData
        {
            get { return noData; }
            set { noData = value; }
        }
        #endregion

        #region Position
        private string position;
        public string Position
        {
            get { return position; }
            set { position = value; }
        }
        #endregion

        #region Top
        private string top;
        public string Top
        {
            get { return top; }
            set { top = value; }
        }
        #endregion

        #region Left
        private string left;
        public string Left
        {
            get { return left; }
            set { left = value; }
        }
        #endregion

        public string GetPositionString()
        {
            System.Text.StringBuilder style=new System.Text.StringBuilder();
            if (!string.IsNullOrEmpty(Position))
                style.Append("position:" + Position+";");
            if (!string.IsNullOrEmpty(Top))
                style.Append("top:" + Top + ";");
            if (!string.IsNullOrEmpty(Left))
                style.Append("left:" + Left + ";");            
            return style.ToString();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnLoad(e);
            if (PassPageParameters)
            {
                Hashtable parameters = Page.Parameters;
                if (parameters != null)
                {
                    foreach (string name in parameters.Keys)
                    {
                        string value = (string)parameters[name];
                        Parameter p = new Parameter();
                        p.Name = name;
                        p.Value = value;
                        Controls.Add(p);
                    }
                }
            }
        }

        public void RenderProperty(HtmlTextWriter writer, string Name, object Value)
        {
            string json = Json.ConvertToJson(Value,false);

            writer.WriteLine(JavascriptId + "."+Name+"=" + json + ";");            
        }

        public void RenderJavascriptId(HtmlTextWriter writer)
        {
			return;
            if(!string.IsNullOrEmpty(JavascriptId))
                writer.WriteLine("var "+JavascriptId+"=" + JavascriptId + ";");            
        }

        public void RenderObjectInit(HtmlTextWriter writer, string ClientName, Delegate DataMethod)
        {
            string DataMethodName = null;
            string DataMethodType = null;

            if (DataMethod != null)
            {
                DataMethodName = DataMethod.Method.Name;
                DataMethodType = DataMethod.Method.DeclaringType.AssemblyQualifiedName;
            }
            writer.WriteLine("var " + JavascriptId + " = new " + ClientName + "('" + JavascriptId + "'," + Json.ConvertToJson(DataMethodType, false) + "," + Json.ConvertToJson(DataMethodName, false) + ");");            
        }

        public new Web.Ajax.Page Page
        {
            get
            {
                return base.Page as Web.Ajax.Page;
            }
            set
            {
                base.Page = value;
            }
        }

        private string javascriptId;
        public string JavascriptId
        {
            get 
			{
				if (string.IsNullOrEmpty(javascriptId))
					return base.ClientID;
				return javascriptId; 
			}
            set { javascriptId = value; }
        }

        public Browser Browser
        {
            get
            {
                string b = Page.Request.Browser.Browser;
                if (b != null)
                {
                    b = b.ToLower();
                    if (b == "firefox")
                        return Browser.FireFox;
                    if (b == "ie")
                    {
                        if (Page.Request.Browser.MajorVersion == 6)
                            return Browser.IE6;
                        if (Page.Request.Browser.MajorVersion == 7)
                            return Browser.IE7;
                    }
                }
                return Browser.Unknown;
            }
        }

        #region DelayLoading
        private bool delayLoading;
        public bool DelayLoading
        {
            get
            {
                Tab t = null;
                if (Parent is Tab)
                    t = Parent as Tab;
                if (t == null && Parent != null)
                {
                    if (Parent.Parent is Tab)
                        t = Parent.Parent as Tab;
                    if (t == null && Parent.Parent != null)
                    {
                        if (Parent.Parent.Parent is Tab)
                            t = Parent.Parent.Parent as Tab;
                    }
                }
                if (t != null)
                    return t.DelayLoading;
                return delayLoading;
            }
            set
            {
                delayLoading = value;
            }
        }
        #endregion

	}

    public class AjaxControlRequest
    {
        public string DataMethodType;
        public string DataMethodName;        
    }

    public class AjaxControlResponse
    {
        public string Message;
        public string OnComplete;
    }

}
